#!/bin/bash
# *************************************
# 功能: 远程主机执行
# 作者: 王树森
# 联系: wangshusen@sswang.com
# 微信群: 自学自讲—软件工程
# 抖音号: sswang_yys 
# 版本: v0.1
# 日期: 2024-07-20
# *************************************

# 环境变量
deploy_log_file="/tmp/deploy.log"
local_ip_addr=$(ip addr | grep 'l e' | head -1 | awk '{print $2}' | awk -F '/' '{print $1}')

# 定制信息输出颜色数字值的获取函数
get_color_num(){
  # 接收参数
  local msg_level="$1"

  if [ "${msg_level}" == "error" ]; then
    local msg_color_num="31"
    local msg_level_context="异常"
  elif [ "${msg_level}" == "warning"  ]; then
    local msg_color_num="33"
    local msg_level_context="提示"
  elif [ "${msg_level}" == "success"  ]; then
    local msg_color_num="32"
    local msg_level_context="成功"
  elif [ "${msg_level}" == "info"  ]; then
    local msg_color_num="37"
    local msg_level_context="正常"
  fi
  echo "${msg_color_num} ${msg_level_context} "
}
# 定制信息输出的功能函数
print::msg(){
  # 帮助信息：print::msg 输出类型 信息级别 输出内容
  # 信息类型：log | console | all
  # 信息级别：info | error | warning | success
  # 接收参数
  local msg_type="$1"
  local msg_level="$2"
  local log_msg=$(echo "$@" | awk '{$1=null; $2=null; print $0}'| awk '$1=$1')

  # 获取其他依赖信息
  read msg_color_num msg_level_context < <(get_color_num "${msg_level}")
  local msg_format="\e[1;${msg_color_num}m[  ${msg_level_context}  ]\e[0m:"

  # 信息输出
  if [ "${msg_type}" == "log" ];then
    printf "$(date "+%Y-%m-%d %T %Z(%z)") ${msg_format} ${local_ip_addr}主机 - ${log_msg}\n" >> ${deploy_log_file}
  elif [ "${msg_type}" == "console" ];then
    printf "${msg_format} ${log_msg}\n"
  elif [ "${msg_type}" == "all" ];then
    printf "$(date "+%Y-%m-%d %T %Z(%z)") ${msg_format} ${local_ip_addr}主机 - ${log_msg}\n" >> ${deploy_log_file}
    printf "${msg_format} ${log_msg}\n"
  fi
}

func1(){
  print::msg "all" "warning" "remote step - 1"
}

func2(){
  print::msg "all" "warning" "remote step - 2"
}

func3(){
  print::msg "all" "warning" "remote step - 3"
}

func4(){
  print::msg "all" "warning" "remote step - 4"
}

main(){
  > ${deploy_log_file}
  func1
  func2
  func3
  func4
}

main
